<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '属性名称为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="属性名称" tooltip="物料属性的名称" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_IsKeyAttribute_FormItem"
							prop="Entity.IsKeyAttribute"
							:rules="[{ required: true, message: '是否关键属性为必填项', trigger: 'blur' }]"
						>
							<template #label>
								<WtmLabelTooltip label="是否关键属性" tooltip="关键属性会生成SKU编码, 非关键属性仅用于采购和领用等辅助识别" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.IsKeyAttribute" clearable class="width100">
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_MaterialId_FormItem" prop="Entity.MaterialId">
							<template #label>
								<WtmLabelTooltip label="物料" tooltip="关联的物料对象" />
							</template>
							<el-input v-model="materialName" :disabled="true" clearable class="width100"></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Order_FormItem" prop="Entity.Order" :rules="[{ required: true, message: '排序为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="排序" tooltip="物料属性的排序字段" />
							</template>
							<el-input-number v-model="stateData.vmModel.Entity.Order" clearable class="width100"></el-input-number>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
							<template #label>
								<WtmLabelTooltip label="备注" tooltip="计量单位组的备注信息" />
							</template>
							<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Remark" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 属性值管理区域 - 仅在保存后显示 -->
		<el-card v-if="stateData.vmModel.Entity.ID" shadow="hover" class="layout-padding-auto mt20">
			<template #header>
				<div class="card-header">
					<span class="card-header-title">属性值管理</span>
				</div>
			</template>

			<!-- 标签输入框快速添加属性值 -->
			<div class="mb20">
				<el-form-item>
					<template #label>
						<WtmLabelTooltip label="快速添加属性值" tooltip="输入属性值后按回车添加，可批量添加多个属性值。删除标签会同步删除记录。" />
					</template>
					<el-input-tag
						v-model="attributeValues"
						:tag-type="'primary'"
						:tag-effect="'plain'"
						placeholder="请输入属性值，按回车添加（如：红色、蓝色、绿色）"
						@change="onAttributeValuesChange"
					/>
				</el-form-item>
				<el-alert type="info" :closable="false" show-icon class="mt10">
					<template #default>
						<p style="margin: 0; font-size: 12px">提示：输入属性值后按回车键即可添加，系统会自动去除重复值。删除标签会同步删除记录。</p>
					</template>
				</el-alert>
			</div>

			<!-- 属性值列表已隐藏，所有操作通过快捷输入框完成 -->
			<!-- <SysMaterialAttributeValue
				ref="sysMaterialAttributeValueRef"
				:search-bar="false"
				:toolbar="true"
				:is-disabled="false"
				:entity-id="stateData.vmModel.Entity.ID"
			/> -->
		</el-card>

		<!-- 提示信息 - 新建时显示 -->
		<el-card v-else shadow="hover" class="layout-padding-auto mt20">
			<el-alert title="提示" type="info" :closable="false" show-icon>
				<template #default>
					<p>请先保存物料属性，然后才能添加属性值。</p>
				</template>
			</el-alert>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysMaterialAttributeApi as api } from '/@/views/supplychain/sysmaterialattribute/api';
import { SysMaterialAttributeValueApi as attributeValueApi } from '/@/views/supplychain/sysmaterialattributevalue/api';
import other from '/@/utils/other';
import { ISysMaterialAttributeVm } from '/@/views/supplychain/sysmaterialattribute/api/interface';
import { IViewModel } from '/@/types/common';
import SysMaterialAttributeValue from '/@/views/supplychain/sysmaterialattributevalue/index.vue';

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');
const materialName = ref<string>(''); // 显示的物料名称
const attributeValues = ref<string[]>([]); // 属性值标签列表
const sysMaterialAttributeValueRef = ref(); // 属性值列表组件引用

const stateData = reactive<IViewModel<ISysMaterialAttributeVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Name: null,
			IsKeyAttribute: false,
			MaterialId: null,
			Remark: null,
			Order: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysMaterials: [],
});

// 保存
const onSave = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				delete submitData.Entity.ID;
			}
			api()
				.add(submitData)
				.then((response) => {
					ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');

					// 尝试多种可能的返回数据结构
					let returnedId = null;

					if (!returnedId) {
						returnedId = (response as any).ID;
					}

					if (returnedId) {
						stateData.vmModel.Entity.ID = returnedId;
						// 使用 nextTick 确保 DOM 更新
						nextTick(async () => {
							// 加载现有的属性值（如果有的话）
							await loadExistingAttributeValues();
							nextTick(() => {
								setupHeaderButtons();
							});
						});
					}

					emit('refresh');
					// 不关闭对话框，让用户可以继续添加属性值
					// closeDialog();
				})
				.catch((error) => {
					other.setFormError(ci, error);
				})
				.finally(() => {
					loading.value = false;
				});
		}
	});
};

// 根据MaterialId设置物料名称
const setMaterialName = () => {
	const materialId = stateData.vmModel.Entity.MaterialId;
	if (materialId) {
		const material = stateData.AllSysMaterials.find((item: any) => item.Value === materialId);
		if (material) {
			materialName.value = material.Text;
		}
	}
};

// 存储上一次的标签值，用于对比
let previousValues: string[] = [];

// 存储属性值与ID的映射关系
const attributeValueIdMap = ref<Map<string, string>>(new Map());

// 处理属性值标签变化
const onAttributeValuesChange = async (newValues: string[]) => {
	// 去重处理：检查是否有重复值
	const uniqueValues = Array.from(new Set(newValues.map((v) => v.trim()).filter((v) => v)));

	// 如果有重复，显示警告并更新为去重后的值
	if (uniqueValues.length !== newValues.length) {
		ElMessage.warning('已自动去除重复的属性值');
		attributeValues.value = uniqueValues;
		return;
	}

	// 找出新增的值
	const addedValues = newValues.filter((v) => !previousValues.includes(v));

	// 找出删除的值
	const removedValues = previousValues.filter((v) => !newValues.includes(v));

	// 如果有新增的值，保存到数据库
	if (addedValues.length > 0) {
		loading.value = true;
		let hasError = false;

		for (const value of addedValues) {
			if (value && value.trim()) {
				try {
					const response = await attributeValueApi().add({
						Entity: {
							AttributeId: stateData.vmModel.Entity.ID || null,
							Value: value.trim(),
						},
					});

					// 保存新创建的属性值ID
					let returnedId = null;

					if (!returnedId) {
						returnedId = (response as any).ID;
					}

					if (returnedId) {
						attributeValueIdMap.value.set(value.trim(), returnedId);
					}
				} catch (error) {
					ElMessage.error(`添加属性值"${value}"失败`);
					hasError = true;
					// 从标签列表中移除失败的值
					attributeValues.value = attributeValues.value.filter((v) => v !== value);
					break;
				}
			}
		}

		loading.value = false;

		if (!hasError) {
			ElMessage.success('属性值添加成功');
		}
	}

	// 如果有删除的值，从数据库中删除
	if (removedValues.length > 0) {
		loading.value = true;
		let hasError = false;

		for (const value of removedValues) {
			const valueId = attributeValueIdMap.value.get(value);
			if (valueId) {
				try {
					await attributeValueApi().delete([valueId]);
					// 删除成功后，从映射中移除
					attributeValueIdMap.value.delete(value);
				} catch (error) {
					ElMessage.error(`删除属性值"${value}"失败`);
					hasError = true;
					// 恢复标签
					attributeValues.value.push(value);
					break;
				}
			}
		}

		loading.value = false;

		if (!hasError && removedValues.length > 0) {
			ElMessage.success('属性值删除成功');
		}
	}

	// 更新上一次的值
	previousValues = [...newValues];
};

// 加载现有的属性值
const loadExistingAttributeValues = async () => {
	if (!stateData.vmModel.Entity.ID) return;

	try {
		const response = await attributeValueApi().search({
			AttributeId: stateData.vmModel.Entity.ID,
			PageIndex: 1,
			PageSize: 1000,
		});

		// 清空现有数据
		attributeValues.value = [];
		attributeValueIdMap.value.clear();

		// 处理响应数据
		let dataList: any[] = [];
		if (response.Data) {
			// 可能是直接的数组
			if (Array.isArray(response.Data)) {
				dataList = response.Data;
			}
		}

		// 加载数据
		dataList.forEach((item: any) => {
			if (item.Value) {
				attributeValues.value.push(item.Value);
				attributeValueIdMap.value.set(item.Value, item.ID);
			}
		});

		// 更新 previousValues
		previousValues = [...attributeValues.value];
	} catch (error) {
		console.error('加载属性值失败:', error);
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	// 初始化数据
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.MaterialId) {
		stateData.vmModel.Entity.MaterialId = wtmdata.MaterialId;
	}
	// 如果是编辑模式，设置 ID
	if (wtmdata?.ID || wtmdata?.Id || wtmdata?.id) {
		stateData.vmModel.Entity.ID = wtmdata.ID || wtmdata.Id || wtmdata.id;
		console.log('编辑模式，ID:', stateData.vmModel.Entity.ID);
	}

	try {
		// 加载物料选择列表
		await other.getSelectList('/api/SysMaterialAttribute/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x));
		// 设置物料名称
		setMaterialName();
		// 如果是编辑模式，加载现有的属性值
		if (stateData.vmModel.Entity.ID) {
			await loadExistingAttributeValues();
		}
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 计算属性：是否有实体ID
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

// 计算属性：是否显示保存按钮（新建模式且未保存过）
const showSaveButton = computed(() => !hasEntityId.value);

// 提交并关闭弹窗
const onSubmit = () => {
	// 先刷新数据，再关闭弹窗
	emit('refresh');
	closeDialog();
};

// 设置头部按钮
const setupHeaderButtons = () => {
	emit('updateHeaderButtons', [
		{ text: '保存', type: 'info', onClick: onSave, visible: showSaveButton.value },
		{ text: '提交', type: 'primary', onClick: onSubmit, visible: !showSaveButton.value },
		{ text: '关闭', type: 'default', onClick: closeDialog, visible: true },
	]);
};
</script>

<style scoped lang="scss">
.mt10 {
	margin-top: 10px;
}

.mt20 {
	margin-top: 20px;
}

.mb20 {
	margin-bottom: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.card-header-title {
		font-size: 16px;
		font-weight: 600;
		color: #303133;
	}
}

:deep(.el-alert__content) {
	p {
		margin: 0;
		line-height: 1.6;
	}
}

:deep(.el-input-tag) {
	width: 100%;
}
</style>
